<!---
Title: 		File Upload
Filename: 	upload.cfm
Description:	Second page in the experiment creation process. An HTML form with postback. Allows users to upload ethics/debrief scripts and stimuli.
--->

<cfinclude template="header.cfm">

<!--- Check a user is logged in. --->
<cfif Not IsDefined("session.id")>
	<cflocation url = "/ecada/index.cfm" addToken = "no">
</cfif>

<!--- Locally store the session ID, if it is defined. --->
<cfif IsDefined("currID")>
	<cfset experimentID=#currID#>
</cfif>

<!--- Check a user's filespace has been created. --->
<cfif Not DirectoryExists("/var/www/html/ecada/users/#session.id#/")>
       <cfdirectory action = "create" directory = "/var/www/html/ecada/users/#session.id#" mode =777 >
</cfif>

<!--- Check the user has a directory for this experiment. --->
<cfif Not DirectoryExists("/var/www/html/ecada/users/#session.id#/#experimentID#")>
       <cfdirectory action = "create" directory = "/var/www/html/ecada/users/#session.id#/#experimentID#" mode =777 >
</cfif>

<cfoutput>
<!--- Form postback. Everything contained within this CFIF will be executed when the user presses 'Upload'. --->
<cfif IsDefined("form.upload")>

	<!--- Page redirect to prevent repeated uploads to same experiment. --->
	<cfif DirectoryExists("/var/www/html/ecada/users/#session.id#/#experimentID#/Condition1")>
		<cfset session.message = "You have already uploaded files for this experiment.">
		<cflocation url="/ecada/ce.cfm">
	</cfif>

	<!---If an ethics file was defined, save it. --->
    	<cfif IsDefined("form.fileup")>	<!---Check that the file field is defined. --->
	    	<cfif #fileup# neq "">
				<cfif FileExists("#fileup#")>	<!---Check that the file about to be uploaded exists. --->
					file exists
					<cffile action="UPLOAD" 
						destination="#ExpandPath('/ecada/users/' & session.id & '/' & experimentID & '/ethics.txt')#" 
						nameconflict="MAKEUNIQUE" 
						filefield="fileup">
				</cfif>
			</cfif>
		</cfif>

		<!--- Insert file path into database, if needed. --->
		<cfif IsDefined("form.fileup")>
			<cfif #fileup# neq "">
				<cfquery name = "addPathET" datasource ="exp">
					UPDATE experiment
					SET ethics = '/ecada/users/#session.id#/#experimentID#/ethics.txt'
					WHERE id = #experimentID#
				</cfquery>
			</cfif>
		</cfif>

		<!--- If a debrief file was defined, save it. --->
		<cfif IsDefined("form.fileupDB")>	<!---Check that the file field is defined. --->
			<cfif #fileupDB# neq "">
				<cfif FileExists("#fileupDB#")>	<!---Check that the file about to be uploaded exists. --->
					file exists
					<cffile action="UPLOAD" 
						destination="#ExpandPath('/ecada/users/' & session.id & '/' & experimentID & '/debrief.txt')#" 
						nameconflict="MAKEUNIQUE" 
						filefield="fileupDB">
				</cfif>
			</cfif>
		</cfif>

		<!--- Insert file path into database, if needed. --->
		<cfif IsDefined("form.fileupDB")>
			<cfif #fileupDB# neq "">
				<cfquery name = "addPathDB" datasource ="exp">
					UPDATE experiment
					SET debrief = '/ecada/users/#session.id#/#experimentID#/debrief.txt'
					WHERE id = #experimentID#
				</cfquery>
			</cfif>
		</cfif>

		<!--- Practice block handling. Practice blocks are fully implemented on the creation side, but no support exists yet for partipants. --->
		<cfif #practice# eq 1>
			<cfset filepathP = "/var/www/html/ecada/users/#session.id#/#experimentID#/Practice/">

			<!--- Upload zipped practice stimuli. --->
			<cffile action="UPLOAD"
				destination="/var/www/html/ecada/users/#session.id#/#experimentID#/practice.zip"
				nameconflict="MAKEUNIQUE"
				filefield="fileupPrac">

			<!--- Create practice stimuli directory. --->	
			<cfif DirectoryExists("/var/www/html/ecada/users/#session.id#/#experimentID#/Practice/")>
			<cfelse>
				<cfdirectory action = "create" directory = #filepathP# mode =777 >
			</cfif>

			<!--- Unzip directory. --->
			<cfzip
				action="unzip"
				file="/var/www/html/ecada/users/#session.id#/#experimentID#/practice.zip"
				destination="/var/www/html/ecada/users/#session.id#/#experimentID#/Practice"
			/>

			<!--- Get file listing for directory. --->
			<cfdirectory 
				directory = #filepathP#
				action = "list"
				name = "getFilesPrac"
			/>

			<!--- Creation of sub-directories for images. --->
			<cfif DirectoryExists("/var/www/html/ecada/users/#session.id#/#experimentID#/Practice/images")>
			<cfelse>
				<cfdirectory action = "create" directory = "#filepathP#images" mode = 777>
			</cfif>

			<!--- Creation of sub-directories for text. --->
			<cfif DirectoryExists("/var/www/html/ecada/users/#session.id#/#experimentID#/Practice/text")>
			<cfelse>
				<cfdirectory action = "create" directory = "#filepathP#text" mode = 777>
			</cfif>

			<!--- Sort files based on file extension. --->
			<h2>Files for Practice Condition</h2>
			<cfset pracdesc = Evaluate("form.pracName")>

			<!--- Create experimental condition. --->
			<cfquery name="pracCond" datasource="exp">
				INSERT INTO expconditions(description, expid)
				VALUES ( "#pracdesc#", #experimentID#)
			</cfquery>

			<cfquery name="getPracID" datasource="exp">
				SELECT MAX(id) as newID
				FROM expconditions
			</cfquery>
			<cfset pracID = getPracID.newID>

			<!--- Text-based trial insertion. Incomplete feature.
			<cfif #pracText# gt 0>
				<cfloop from="1" to="#pracText#" index="i">
					<cfquery datasource ="exp">
						INSERT INTO stimuli( location, istext, question )
						VALUES("T.PNG", 1, "default" ) 
					</cfquery>
				
					<cfquery name="getStimID" datasource="exp">
						SELECT MAX(id) as newID
						FROM stimuli
					</cfquery>
					<cfset stimID = getStimID.newID>

					<cfquery datasource ="exp">
						INSERT INTO trial( condid, expid, partid, stimid )
						VALUES( #pracID#, #experimentID#, 0, #stimID# ) 
					</cfquery>
				</cfloop>	
			</cfif> --->

			<cfloop query="getFilesPrac">
				<cfset extension= Right(#getFilesPrac.NAME#, 3)>

				<!--- Move PNGs and JPGs to /images, TXT to /text, delete everything else. --->
				<cfif #extension# is "PNG" or #extension# is "JPG">
					
					<cffile action="move"
						source="#getFilesPrac.DIRECTORY#/#getFilesPrac.NAME#"
						destination="/var/www/html/ecada/users/#session.id#/#experimentID#/Practice/images/#getFilesPrac.NAME#">

					<cfquery datasource="exp">
						<!--- Insert stimuli and trial info into the database. --->	
						INSERT INTO stimuli( location, ispicture, question )
						VALUES( "users/#session.id#/#experimentID#/Practice/images/#getFilesPrac.NAME#", 1, "default" ) 
						
						<!--- Get stimuli's ID. --->
						<cfquery name="getNewID" datasource="exp">
							SELECT MAX(id) as newID
							FROM stimuli
						 </cfquery>
						 <cfset stimID = getNewID.newID>
						 
						 <cfquery name="insertStim" datasource="exp">
						 	INSERT INTO trial( expid, stimid, condid, partid, answerradio, answerlikert )
						 	VALUES( #experimentID#, #stimID#, #pracID#, 0, 0, 0 ) 
						 </cfquery> 
					</cfquery>
					<!--- <img src="users/#session.id#/#experimentID#/Practice/images/#getFilesPrac.NAME#" width="100" height="100"> --->
					<cfoutput><b> #getFilesPrac.NAME#</b> has been received.<br></cfoutput>
			
				<!--- Create a new block. --->
				<cfquery name="insertPracBlock" datasource="exp">
					INSERT INTO block( expid, partid, ispractice, isquestion )
					VALUES( #experimentID#, 0, 1, 0 ) 
				</cfquery> 			

				<!--- Unwanted file disposal. --->
				<cfelse>
					<cfif #getFilesPrac.TYPE# is "File">
						<cffile action="delete"
							file="#getFilesPrac.DIRECTORY#/#getFilesPrac.NAME#">
							<!---<img src="R.png" width="100" height="100">--->
							<cfoutput><b>#getFilesPrac.NAME#</b> has been discarded.<br></cfoutput>	
					</cfif>
				</cfif>
				
			</cfloop>
		
	</cfif> 
	<!--- End of practice block insertion. --->	

	<!--- File insertion for conditions. --->        
   	<cfloop from="1" to="#conditions#" index="i">
		
		<cfset filepathC = "/var/www/html/ecada/users/#session.id#/#experimentID#/Condition#i#">
			
		<cfif #evaluate("fileupS" & i)# neq ""> 
			<!--- Upload zip. --->
			<cffile action="UPLOAD"
				destination="/var/www/html/ecada/users/#session.id#/#experimentID#/Condition#i#.zip"
				nameconflict="MAKEUNIQUE"
				filefield="fileupS#i#">
			
			<!--- Create stimuli directory. --->	
			<cfif DirectoryExists("/var/www/html/ecada/users/#session.id#/#experimentID#/Condition#i#/")>
				<!--- Do nothing --->
			<cfelse>
				<cfdirectory action = "create" directory = "/var/www/html/ecada/users/#session.id#/#experimentID#/Condition#i#/" mode =777 >
			</cfif>

			<!--- Unzip uploaded stimuli. --->
				<cfzip
					action="unzip"
					file="/var/www/html/ecada/users/#session.id#/#experimentID#/Condition#i#.zip"
					destination="/var/www/html/ecada/users/#session.id#/#experimentID#/Condition#i#"
				/>
		</cfif>

		<!--- Get file listing for the directory. --->
		<cfdirectory 
			directory = "/var/www/html/ecada/users/#session.id#/#experimentID#/Condition#i#"
			action = "list"
			name = "getFiles"
		/>

		<!--- creation of sub-directories for images --->
		<cfif DirectoryExists("/var/www/html/ecada/users/#session.id#/#experimentID#/Condition#i#/images")>
			<!--- Do nothing. --->
		<cfelse>
			<cfdirectory action = "create" directory = "/var/www/html/ecada/users/#session.id#/#experimentID#/Condition#i#/images" mode = 777>
		</cfif>
		
		<!--- Creation of sub-directories for text. --->
		<cfif DirectoryExists("/var/www/html/ecada/users/#session.id#/#experimentID#/Condition#i#/text")>
		<cfelse>
			<cfdirectory action = "create" directory = "/var/www/html/ecada/users/#session.id#/#experimentID#/Condition#i#/text" mode = 777>
		</cfif>
					
		<!--- Sort files based on file extension. --->
		<h2>Files for Condition #i#</h2>
		<cfset condesc = Evaluate("form.condesc#i#")>
		 
		<!--- Create experimental condition. --->
		<cfquery name="cond" datasource="exp">
			INSERT INTO expconditions(description, expid)
			VALUES ( "#condesc#", #experimentID#)
		</cfquery>
	
		<cfquery name="getCondID" datasource="exp">
			SELECT MAX(id) as newID
			FROM expconditions
		</cfquery>
		<cfset condID = getCondID.newID>

		<!--- Inserting text-only trials. Incomplete feature. --->
		<!---		
		<cfset condText = Evaluate("form.condText#i#")>
		<cfif #condText# gt 0>
			<cfloop from="1" to="#condText#" index="j">
				<cfquery datasource ="exp">
					INSERT INTO stimuli(location, istext, question )
        				VALUES("T.PNG", 1, "default" ) 
				</cfquery>
				
				<cfquery name="getStimID" datasource="exp">
        				SELECT MAX(id) as newID
        				FROM stimuli
        			</cfquery>
        			<cfset stimID = getStimID.newID>

				<cfquery datasource ="exp">
					INSERT INTO trial( condid, expid, partid, stimid )
        				VALUES( #condID#, #experimentID#, #i#, #stimID# ) 
				</cfquery>
				
			</cfloop>	
		</cfif> --->
        		
		<cfloop query="getFiles">
			<cfset extension= Right(#getFiles.NAME#, 3)> <!--- Get the last three characters of the filename - TXT, JPG, ETC --->
			
			<!--- Move PNGs and JPGs to /images, txt to /text, delete everything else --->
			<cfif #extension# is "PNG" or #extension# is "JPG">
				
				<cffile action="move"
					source="#getFiles.DIRECTORY#/#getFiles.NAME#"
					destination="/var/www/html/ecada/users/#session.id#/#experimentID#/Condition#i#/images/#getFiles.NAME#">

				<cfquery datasource="exp">
					<!--- Insert stimuli and trial info into the database. --->	
					INSERT INTO stimuli( location, ispicture, question )
					VALUES( "users/#session.id#/#experimentID#/Condition#i#/images/#getFiles.NAME#", 1, "default" ) 
					
					<!--- Gets stimuli's ID. --->
					<cfquery name="getNewID" datasource="exp">
						SELECT MAX(id) as newID
						FROM stimuli
					 </cfquery>
					 <cfset stimID = getNewID.newID>

					<!--- Insert stimuli into database. --->
					 <cfquery name="insertStim" datasource="exp">
					 	INSERT INTO trial( expid, stimid, condid, partid, answerradio, answerlikert )
					 	VALUES( #experimentID#, (#stimID#+1), #condID#, #i#, 0, 0 ) 
					 </cfquery> 
				</cfquery>
				<img src="users/#session.id#/#experimentID#/Condition#i#/images/#getFiles.NAME#" width="100" height="100">
				<cfoutput><b> #getFiles.NAME#</b> has been received.<br></cfoutput>

		<!--- Create a new block in the database. --->
		<cfquery name="insertBlock" datasource="exp">
			INSERT INTO block( expid, partid, ispractice, isquestion )
			VALUES( #experimentID#, #i#, 0, 0 ) 
		</cfquery>
		
		<!--- Unwanted file disposal. --->
		<cfelse>
			<cfif #getFiles.TYPE# is "File">
				<cffile action="delete"
					file="#getFiles.DIRECTORY#/#getFiles.NAME#">
					<!---<img src="R.png" width="100" height="100">--->
					<cfoutput><b>#getFiles.NAME#</b> has been discarded.<br></cfoutput>	
			</cfif>
		</cfif>
        	</cfloop>   
        </cfloop>
        
        <!--- ZIP cleaner. Removes the .zips that were uploaded to the server. --->
        <cfdirectory 
        	directory = "/var/www/html/ecada/users/#session.id#/#experimentID#/"
        	action = "list"
        	name = "getRubbish"
        />
        
        <cfloop query = "getRubbish">
        	<cfset extension= Right(#getRubbish.NAME#, 3)>
        	<cfif extension eq "zip">
             <cffile action="delete"
                             file="#getRubbish.DIRECTORY#/#getRubbish.NAME#">
             </cfif>
        </cfloop>
        
        <!--- Move on to next page.--->
        <cfheader statuscode="301" statustext="Moved Permanently">
        <cfheader name="Location" value="EE.cfm?currID=#experimentID#">
        <cfabort>
        
        <br>
        <input type="button" value="Next" onClick="window.location.href='EE.cfm'">
        
<!--- Everything contained in this CFELSE tag will be displayed when the user first sees the page. --->
<cfelse>
	<!--- Checks that the parameters being passed to the page have been defined. --->
	<cfif not isDefined("currID")>
	<cfset session.message = "No experiment specified">
	<cflocation url="/ecada/index.cfm">
	</cfif>

	<cfif not isDefined("cNum")>
	<cfset session.message = "Number of conditions not specified">
	<cflocation url="/ecada/index.cfm">
	</cfif>

        <cfoutput> 
	<!--- Help blurb. --->  
        Upload your stimuli here, zipping stimuli by condition. Each condition must have the same number of stimuli. Optionally, you can also specify a number of text-based trials. For more specific instructions, see <a href="http://bantayan.dcs.gla.ac.uk/ecada/help.cfm">the help page.</a><br>
        <ul>
        <li>Supported images: jpg, png</li>
        </ul>

	<!--- Upload form. --->
        <form method = "post" id="form1" name="form1"action = "upload.cfm" enctype="multipart/form-data">      
                 <table>
                 <tr><h2>Condition stimuli</h2></tr>

		<!--- Ethics and debrief script upload. --->
		<tr>
		<td id="fileupTT">	Upload ethics form       :</td>
		<td><input type="File" name="fileup"/></td>
		</tr>

		<tr>
		<td id="fileupDB">	Upload debrief form       :</td>
		<td><input type="File" name="fileupDB"/></td>
		</tr>

		<tr><td></td></tr><tr><td></td></tr> <!--- Table whitespace. --->

		<!--- Practice block upload form.--->
		<cfif prac eq 1>				
		<tr>
                   <td id="pracTT">Stimuli for practice block :</td>
                   <td><input type="File" name="fileupPrac"/></td>
                   </tr>
                   
                   <tr>
                   <td id="pracNameTT">Practice block description : </td>
                   <td><input type = "text"size = "30" id="pracName" name="pracName"></td>
                   </tr>

		   <tr>
                   <td id="practtextTT">Number of text-based trials for practice block <font color="red">(Disabled)</font>: </td>
                   <td><input type = "text"size = "30" id="pracText" name="pracText" disabled="true"></td>
                   </tr>
		</cfif> 

		<!--- Dynamically generate the required number of form fields based on the number of conditions that have been passed. --->
                 <cfloop from="1" to="#cNum#" index="i">
                   <tr>
                   <td id="fileupStim#i#">Stimuli for condition #i# :</td>
                   <td><input type="File" name="fileupS#i#"/></td>
                   </tr>
                   
                   <tr>
                   <td id="condName#i#TT">Condition #i# description : </td>
                   <td><input type = "text"size = "30" id="condesc#i#" name="condesc#i#"></td>
                   </tr>

		   <tr>
                   <td id="condtextTT">Number of text-based trials for condition #i# <font color="red">(Disabled)</font> : </td>
                   <td><input type = "text"size = "30" id="condText#i#" name="condText#i#" disabled="true"></td>
                   </tr>

                   </cfloop>
                 <td><input type = "submit" name="upload" value = "Upload"></td>
                 </table>
                 <input type = "text" id="cond" name="conditions"  value = "#cNum#" style="display: none;">
                 <input type = "text" id="expid" name="experimentID"  value = "#currID#" style="display: none;">
		 <input type = "text" id="prac" name="practice"  value = "#prac#" style="display: none;">             
        </form>     
        </cfoutput>
</cfif>
</cfoutput>
<cfinclude template="footer.cfm">
